package part1;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

/**
 * 访问网站：http://www.rest7.com/，编写程序用该网站提供的my_ip接口，查询本机IP
 * url: http://api.rest7.com/v1/my_ip.php
 */
public class Q1 {

    /**
     * 通过 URL 对象获取本地 IP
     *
     * @return IP
     */
    public static List<String> getLocalIpByURL() throws IOException {
        final URL url = new URL("http://api.rest7.com/v1/my_ip.php");
        final byte[] bytes = url.openStream().readAllBytes();
        return new Gson().fromJson(new String(bytes), new TypeToken<List<String>>() {
        }.getType());
    }

    /**
     * 通过 HttpClient 对象获取本地 IP
     *
     * @return IP
     */
    public static List<String> getLocalIpByHttpClient() throws IOException, InterruptedException {
        final HttpClient httpClient = HttpClient.newHttpClient();
        final HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create("http://api.rest7.com/v1/my_ip.php")).build();
        final HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        final String body = httpResponse.body();
        return new Gson().fromJson(body, new TypeToken<List<String>>() {
        }.getType());
    }

}
